package thread.deadlock;

import java.util.concurrent.TimeUnit;

/**
 * @author jiangwz
 * @create 2019/9/16.
 */
public class DeadLockDemo {

    /**
     * 排查死锁 jps -l 找到运行程序的pid
     * 然后 jstack pid
     * Java stack information for the threads listed above:
     * ===================================================
     * "Thread-1":
     *         at thread.deadlock.DeadLockResource.run(DeadLockDemo.java:38)
     *         - waiting to lock <0x000000076b14c168> (a java.lang.String)
     *         - locked <0x000000076b14c198> (a java.lang.String)
     *         at java.lang.Thread.run(Thread.java:748)
     * "Thread-0":
     *         at thread.deadlock.DeadLockResource.run(DeadLockDemo.java:38)
     *         - waiting to lock <0x000000076b14c198> (a java.lang.String)
     *         - locked <0x000000076b14c168> (a java.lang.String)
     *         at java.lang.Thread.run(Thread.java:748)
     *
     * Found 1 deadlock.
     *
     * 就可以看到死锁
     * @param args
     */
    public static void main(String[] args){
      String lockA = "a";
      String lockB = "b";
      new Thread(new DeadLockResource(lockA,lockB)).start();
      new Thread(new DeadLockResource(lockB,lockA)).start();

    }

}

class DeadLockResource implements Runnable{

    private String lockA;
    private String lockB;

    public DeadLockResource(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }


    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "线程获取到"+lockA+",尝试获取lockB");
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName() + "线程获取到" + lockB);
            }
        }
    }
}
